<template>
  <div class="pdf-con">
    <div class="pdf-div" ref="pdfDiv" v-loading="loading" element-loading-text="加载中">
      <template v-if="base64 && numPages > 0">
        <template v-for="i in numPages">
          <pdf v-if="i == 1" 
            :key="i" :id="'pdf-' + i"
            :src="base64"
            :page="i"
            @page-loaded="firstPageLoaded"></pdf>
          <pdf v-else
            :key="i" :id="'pdf-' + i"
            :src="base64"
            :page="i"></pdf>
        </template>
      </template>
    </div>
    <!-- <div class="pdf-page">
      <el-button type="text" @click.stop="prePage">上一页</el-button>
      <div style="margin: 0 8px">{{ currentPage }}/{{ numPages }}</div>
      <el-button type="text" @click.stop="nextPage">下一页</el-button>
    </div> -->
  </div>
</template>
<script>
import pdf from 'vue-pdf';
import CMapReaderFactory from 'vue-pdf/src/CMapReaderFactory.js';
// import { Loading } from 'vant';
// Vue.use(Loading);

export default {
  name: 'ins-docs-pdf',
  props: {
    src: {
      type: String, //默认值，选中值
      default: '',
    },
  },
  data() {
    return {
      loading: true, //加载中
      loadingError: false, //加载失败
      numPages: 0, //分页
      currentPage: 1, //当前显示页数
      base64: ''
    };
  },
  watch: {
    src: {
      deep: true,
      immediate: true,
      handler(val) {
        if (val) {
          this.loadingPdfToBase64(val);
        }
      },
    },
  },
  components: {
    pdf,
  },
  methods: {
    loadingPdfToBase64(url) {
      this.loading = true;
      let that = this;
      fetch(url)
        .then(response => response.blob())
        .then(blob => {
          const reader = new FileReader();
          reader.onloadend = function() {
            that.base64 = reader.result;
            that.getPDFnums(that.base64);
          };
          reader.readAsDataURL(blob);
        })
    },
    //计算pdf页码总数
    getPDFnums(url) {
      //let loadURL = pdf.createLoadingTask(url)
      let loadURL = pdf.createLoadingTask({
        url: url, //你的pdf地址
        CMapReaderFactory,
      });

      loadURL.promise
        .then((pdf) => {
          this.numPages = pdf.numPages;
          // this.$set(this, 'docsPDF.numPages', pdf.numPages);
        });
    },
    firstPageLoaded() {
      this.loading = false;
    },
    // 上一页
    prePage() {
      var page = this.currentPage;
      page = page > 1 ? page - 1 : this.numPages;
      this.currentPage = page;
      // this.$refs.pdfDiv.scrollTop = 0;
      this.toPage(page);
    },

    // 下一页
    nextPage() {
      var page = this.currentPage;
      page = page < this.numPages ? page + 1 : 1;
      this.currentPage = page;
      // this.$refs.pdfDiv.scrollTop = 0;
      this.toPage(page);
    },

    toPage(page) {
      document.getElementById('pdf-' + page).scrollIntoView({behavior: 'smooth'});
    },

    // 回调
    loadPdfHandler(e) {
      this.currentPage = 1;
    },

    getCurrentPage() {
      var parentElement = this.$refs.pdfDiv; //document.getElementById('parentElement');
      var scrollTop = parentElement.scrollTop;
      var parentHeight = parentElement.clientHeight;
      var currentPage = 1;

      // 计算在视野中间的子元素
      var children = parentElement.querySelectorAll('[id^="pdf"]');
      Array.prototype.forEach.call(children, function(child, index) {
        var childTop = child.offsetTop - parentElement.offsetTop;
        var childHeight = child.clientHeight;
        if (childTop <= (scrollTop + parentHeight / 2) && (childTop + childHeight) >= (scrollTop + parentHeight / 2)) {
          // 在视野中间的子元素
          currentPage = index + 1;
        }
      });
      return currentPage;
    }
  },
};
</script>
<style lang="scss" scoped>
.pdf-con {
  width: 100%;
  height: 100%;
  .pdf-div {
    width: 100%;
    height: calc(100% - 1px);
    overflow-y: auto;
    position: relative;
  }
  .pdf-page {
    width: 100%;
    height: 20px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }
}
</style>
